<template>
    <div class="p-2">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="110">
              <el-form-item label="客户" prop="supplierId">
                <el-select filterable v-model="queryParams.supplierId" clearable reserve-keyword placeholder="请选择客户">
                  <el-option v-for="item in userList" :key="item.id" :label="item.supplierName" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="插件" prop="pluginsId">
                <el-select filterable v-model="queryParams.pluginsId" clearable reserve-keyword placeholder="请选择插件" @keyup.enter="handleQuery">
                  <el-option v-for="item in pluginsList" :key="item.id" :label="item.pluginsName" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="密钥KEY" prop="secretKey">
                <el-input v-model="queryParams.secretKey" placeholder="请输入密钥KEY" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>
  
      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['order:pluginsSecretKey:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['order:pluginsSecretKey:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['order:pluginsSecretKey:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['order:pluginsSecretKey:export']">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>
  
        <el-table v-loading="loading" :data="pluginsSecretKeyList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="客户名称" align="center" prop="supplierName" />
          <el-table-column label="插件名称" align="center" prop="pluginsName" />
          <el-table-column label="密钥KEY" align="center" prop="secretKey" width="350"/>
          <el-table-column label="过期时间" align="center" prop="expirationTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.expirationTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="密钥状态" align="center" prop="secretKeyStatus" >
            
            <template #default="scope">
                <el-tag v-if="scope.row.secretKeyStatus == 0" type="info">未使用</el-tag>
                <el-tag v-else-if="scope.row.secretKeyStatus == 1" type="success">已使用</el-tag>
                </template>
          </el-table-column>
          <el-table-column label="开始使用时间" align="center" prop="useStartTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.useStartTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否发放" align="center" prop="grantStatus" >
            <template #default="scope">
                <el-tag v-if="scope.row.grantStatus == 0" type="info">未发放</el-tag>
                <el-tag v-else-if="scope.row.grantStatus == 1" type="success">已发放</el-tag>
                </template>

          </el-table-column>
          <!-- <el-table-column label="所属租户编号" align="center" prop="useTenantId" /> -->
          <el-table-column label="有效天数" align="center" prop="expirationDate" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:pluginsSecretKey:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:pluginsSecretKey:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
  
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
      <!-- 添加或修改插件密钥对话框 -->
      <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
        <el-form ref="pluginsSecretKeyFormRef" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="选择插件" prop="pluginsId" @click="showPlugins">
            <el-input v-model="form.pluginsName" placeholder="请选择插件" :suffix-icon="Search"/>
          </el-form-item>               
          <el-form-item label="选择客户" prop="supplierName"  @click="showCustomer">
            <el-input v-model="form.supplierName" placeholder="请选择客户" :suffix-icon="Search"/>
          </el-form-item>          
          <el-form-item label="密钥KEY" prop="secretKey">
            <el-input disabled v-model="form.secretKey" placeholder="请输入密钥KEY" />
          </el-form-item>
          <el-form-item label="开始时间" prop="useStartTime">
            <el-date-picker clearable
              v-model="form.useStartTime"
              @change="numChange"
              style="width: 100%;"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开始时间">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="有效天数" prop="expirationDate">
            <el-input @change="numChange" type="number" v-model="form.expirationDate" placeholder="请输入有效天数" />
          </el-form-item>
          <el-form-item label="过期时间" prop="expirationTime">
            <el-date-picker clearable
            disabled
              style="width: 100%;"
              v-model="form.expirationTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择过期时间">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="发放状态" prop="grantStatus">
            <el-switch
    v-model="form.grantStatus"
    class="ml-2"
    active-value="1"
    inactive-value="0"

    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
  />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
      <custom-dialog ref="customDialogRef" @ok="customerOk"></custom-dialog>
      <plugins-dialog ref="pluginsDialogRef" @ok="pluginsOk"></plugins-dialog>
    </div>
  </template>
  
  <script setup name="PluginsSecretKey" lang="ts">
  import { listPluginsSecretKey, getPluginsSecretKey, delPluginsSecretKey, addPluginsSecretKey, updatePluginsSecretKey } from '@/api/goods/pluginsSecretKey';
  import { PluginsSecretKeyVO, PluginsSecretKeyQuery, PluginsSecretKeyForm } from '@/api/goods/pluginsSecretKey/types';
  import { listPlugins } from '@/api/goods/plugins';
  import { getSupplierAllList } from '@/api/goods/supplier/index';
  import { randomString } from '@/utils/util'
  import moment from 'moment'
  import { Search } from '@element-plus/icons-vue'
  import customDialog from '@/views/goods/customer/modules/custom-dialog.vue';
  import pluginsDialog from '@/views/goods/plugin/modules/pluginsDialog.vue';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  
  const pluginsSecretKeyList = ref<PluginsSecretKeyVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const pluginsList = ref([])
  const userList = ref([])

  
  const queryFormRef = ref<ElFormInstance>();
  const pluginsSecretKeyFormRef = ref<ElFormInstance>();
  
  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  
  const initFormData: PluginsSecretKeyForm = {
    id: undefined,
    pluginsId: undefined,
    secretKey: undefined,
    expirationTime: undefined,
    secretKeyStatus: undefined,
    useStartTime: undefined,
    grantStatus: undefined,
    useTenantId: undefined,
    expirationDate: undefined,
    supplierId:undefined,
    supplierName:undefined,

  }
  const data = reactive<PageData<PluginsSecretKeyForm, PluginsSecretKeyQuery>>({
    form: {...initFormData},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      supplierId: undefined,
      pluginsId: undefined,
      secretKey: undefined,
      expirationTime: undefined,
      secretKeyStatus: undefined,
      useStartTime: undefined,
      grantStatus: undefined,
      useTenantId: undefined,
      expirationDate: undefined,
      params: {
      }
    },
    rules: {
      id: [
        { required: true, message: "主键id不能为空", trigger: "blur" }
      ],
      pluginsId: [
        { required: true, message: "插件不能为空", trigger: "blur" }
      ],
      secretKey: [
        { required: true, message: "密钥KEY不能为空", trigger: "blur" }
      ],
      expirationTime: [
        { required: true, message: "过期时间不能为空", trigger: "blur" }
      ],
      secretKeyStatus: [
        { required: true, message: "密钥状态：0代表未使用，1代表已使用不能为空", trigger: "change" }
      ],
      useStartTime: [
        { required: true, message: "开始使用时间不能为空", trigger: "blur" }
      ],
      grantStatus: [
        { required: true, message: "是否发放：0代表未发放，1代表已发放不能为空", trigger: "change" }
      ],
      useTenantId: [
        { required: true, message: "所属租户编号不能为空", trigger: "blur" }
      ],
      expirationDate: [
        { required: true, message: "有效天数不能为空", trigger: "blur" }
      ],
    }
  });
  
  const { queryParams, form, rules } = toRefs(data);
  
  /** 查询插件密钥列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listPluginsSecretKey(queryParams.value);
    pluginsSecretKeyList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }
  const getPlusgins = async () => {
    const res = await listPlugins({pageNum:1,pageSize:999999})
    pluginsList.value = res.rows

  }
  const getCustomers = async () => {
    const res = await getSupplierAllList({pageNum:1,pageSize:999999,type:1})
    userList.value = res

  }
  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }
  
  /** 表单重置 */
  const reset = () => {
    form.value = {...initFormData};
    pluginsSecretKeyFormRef.value?.resetFields();
  }
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }
  
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }
  
  /** 多选框选中数据 */
  const handleSelectionChange = (selection: PluginsSecretKeyVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  
  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加插件密钥";
    form.value.secretKey = randomUUID()
    form.value.useStartTime = moment().format('YYYY-MM-DD HH:mm:ss')
    form.value.expirationDate = 30
    form.value.expirationTime = moment(form.value.useStartTime).add(form.value.expirationDate, 'days').format('YYYY-MM-DD HH:mm:ss')
    form.value.secretKeyStatus = '0'
    form.value.grantStatus = '0'



  }
  
  /** 修改按钮操作 */
  const handleUpdate = async (row?: PluginsSecretKeyVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getPluginsSecretKey(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改插件密钥";
  }
  
  /** 提交按钮 */
  const submitForm = () => {
    pluginsSecretKeyFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updatePluginsSecretKey(form.value).finally(() =>  buttonLoading.value = false);
        } else {
          await addPluginsSecretKey(form.value).finally(() =>  buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      }
    });
  }
  
  /** 删除按钮操作 */
  const handleDelete = async (row?: PluginsSecretKeyVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除插件密钥编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delPluginsSecretKey(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }
  
  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('order/pluginsSecretKey/export', {
      ...queryParams.value
    }, `pluginsSecretKey_${new Date().getTime()}.xlsx`)
  }
  const randomUUID =()=>{
    let chats = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

    return randomString(64, chats)
  }
  const numChange = (val:any)=>{
    form.value.expirationTime = moment(form.value.useStartTime).add(form.value.expirationDate, 'days').format('YYYY-MM-DD HH:mm:ss')
  }
  const showCustomer =()=> {
      proxy.$refs.customDialogRef.open();
  }
  const showPlugins =()=> {
      proxy.$refs.pluginsDialogRef.open();
  }
  const customerOk=(rows)=> {
      let customer = rows[0];
      form.value.supplierId = customer.id;
      form.value.supplierName = customer.supplierName;
    }
  const pluginsOk=(rows)=> {
      let plugin = rows[0];
      form.value.pluginsId = plugin.id;
      form.value.pluginsName = plugin.pluginsName;
    }
  onMounted(() => {
    getList();
    getPlusgins()
    getCustomers()
  });
  </script>
  